let app = getApp()
const db = wx.cloud.database({
  env: app.globalData.CLOUD_ENV
})
// 获取操作面试题数据表的对象（面试题数据集合）
const todolist = db.collection('todolist')

let delay = null

Page({

  /**
   * 页面的初始数据
   */
  data: {
    a: 0,
    b: 0,
    arr: [
      // {
      //   checked: false,
      //   text: '名称1',
      //   start_time: 0,
      //   openid: '',
      //   task_id: ''
      // },
    ],
    show: false,
    show3: false,
    message: '',
    task_id: '',
    sx: 0,
    x: 0,
    i: -1,
  },
  startFn(e){
    //  console.log(e.changedTouches[0].pageX);
     if(!e.changedTouches[0]) return;
     this.setData({
       sx: e.changedTouches[0].pageX
     })
  },
  moveFn(e){
    // let index = e.currentTarget.dataset.index;
    var mx = e.changedTouches[0].pageX;
    // let arr = this.data.arr;
    var x = mx - this.data.sx;
    // arr[index].distX = 180 - Math.abs(x);
    this.setData({
      x: x,
      // arr
    })
  },
  endFn(e){
    // console.log(e.currentTarget.dataset.index)
    // console.log(this.data.x)
    let index = e.currentTarget.dataset.index;
    let x = this.data.x;
    let arr = this.data.arr;
    if(x < 0) {
      arr[index].isShow = true;
      arr[index].distX = 0;
      this.setData({
        i: index,
        arr
      })
    }else {
      arr[index].isShow = false;
      arr[index].distX = 180;
      this.setData({
        i: -1,
        arr
      })
    }
  },
  onOpen() {
    this.setData({
      show: true
    })
  },
  onClose() {
    this.setData({
      show: false
    })
  },
  onClose3(){
    this.setData({
      show3: false
    })
  },
  onChange(e) {
    let v = e.detail
    // console.log({v})
    this.setData({
      message: v
    })
  },
  onChange3(e) {
    let v = e.detail
    // console.log({v})
    this.setData({
      message: v
    })
  },

  async updateFn(event) {
    let index = event.currentTarget.dataset.index;
    let task_id = event.currentTarget.dataset.id;
    let that = this;
    let arr = this.data.arr;
    if (arr[index].checked) {
      await todolist.where({
        task_id
      })
      .update({
        data: {
          checked: false,
        }
      }).then(
        rows => {
          // console.log(3.0, rows)
          if (rows.errMsg == "collection.update:ok" || rows.errMsg == "document.update:ok") {
            wx.showToast({
              title: '还未完成计划。',
              icon: 'none'
            })
            arr[index].checked = false;
            arr[index].distX = false;
            this.setData({
              arr
            });
            that.taskList();
            that.initFn();
          } else {
            wx.showToast({
              title: '修改失败。',
              icon: 'none'
            })
          }
        },
        err => {
          console.log(err)
        }
      )
    } else {
      await todolist.where({
        task_id
      })
      .update({
        data: {
          checked: true,
        }
      }).then(
        rows => {
          // console.log(3.0, rows)
          if (rows.errMsg == "collection.update:ok" || rows.errMsg == "document.update:ok") {
            wx.showToast({
              title: '已完成计划。',
              icon: 'none'
            })
            arr[index].checked = true;
            this.setData({
              arr
            });
            that.taskList();
            that.initFn();
          } else {
            wx.showToast({
              title: '修改失败。',
              icon: 'none'
            })
          }
        },
        err => {
          console.log(err)
        }
      )
      
    }

  },

  onChange3(e) {
    let v = e.detail
    // console.log({v})
    this.setData({
      message: v
    })
  },

  // 列表
  async taskList() {
    let openid = wx.getStorageSync('openid')
    if (!openid) {
      return;
    }
    let res = await todolist.where({
      openid
    }).count()
    let count = res.total;
    // console.log({count});
    let all = []; 
    for (let i = 0; i < count; i += 20) {
      await todolist.where({openid}).skip(i).get()
        .then(
          content => {
            let {
              data
            } = content;
            if (data.length != 0) {
              all = all.concat(data)
            }
          }
        )
    }

   var newArr = all.map(item=>{
      item.isShow = false;
      item.distX = 180;
      return item;
    })

    this.setData({
      arr: newArr,
    })
  },

  // 新增
  addTask() {
   
    if(delay != null) {
      clearTimeout(delay);
    }
    delay = setTimeout(()=>{
      let value = this.data.message;
      let that = this;
      if (value == "") {
        wx.showToast({
          title: '输入框不能为空。',
          icon: 'none'
        })
        return;
      }
      let openid = wx.getStorageSync('openid')
      //  console.log({openid})
      let option = {
        value
      }
      // wx.showLoading({
      //   title: '正在添加...',
      //   icon: 'none'
      // })
      if (openid) {
        // 检测敏感词
        wx.cloud.callFunction({
          name: 'msgsec',
          data: {
            content: JSON.stringify(option),
            openid
          },
          async success(res) {
            let {
              result: {
                errCode,
                errMsg
              }
            } = res;
            // console.log('检测结果:',res);//  errCode == 0 表示文本正常
            if (errCode == 0) {
              // 添加计划
              await todolist
                .add({
                  data: {
                    checked: false,
                    text: value,
                    start_time: new Date().getTime(),
                    openid,
                    task_id: Math.random().toString().slice(2) + "_" + (new Date().getTime()).toString().slice(-4)

                  }
                }).then(
                  rows => {
                    // console.log(3.0, rows)
                    if (rows.errMsg == "collection.add:ok" || rows.errMsg == "document.add:ok") {
                      wx.showToast({
                        title: '添加计划成功。',
                        icon: 'none'
                      })
                      that.setData({
                        show: false,
                        message: ''
                      })
                      that.taskList();
                      that.initFn();
                    } else {
                      wx.showToast({
                        title: '添加计划失败。',
                        icon: 'none'
                      })
                    }
                  },
                  err => {
                    console.log(err)
                  }
                )
            } else {
              if (errMsg != "openapi.security.msgSecCheck:ok") {
                wx.showToast({
                  title: '您输入的内容包含敏感词哦。',
                  icon: 'none'
                })
              } else {
                wx.showToast({
                  title: `${errMsg},${errCode}`,
                  icon: 'none'
                })
              }
            }

            delay = null;
            wx.hideLoading();
          }
        })
      } else {
        wx.showToast({
          title: '请先登录再写计划。',
          icon: 'none'
        })
       delay = null;
      }
    },500)
  },
  // 初始化数量
  async initFn(){
    let openid = wx.getStorageSync('openid')
    let aaa = await todolist.where({
      openid,
      checked: false
    }).count()

    let bbb = await todolist.where({
      openid,
      checked: true
    }).count()

    this.setData({
      a:aaa.total,
      b: bbb.total 
    })
  },
  // 修改名称
  editTask() {
    let value = this.data.message;
    let task_id = this.data.task_id;
    let that = this;
    if (value == "") {
      wx.showToast({
        title: '输入框不能为空。',
        icon: 'none'
      })
      return;
    }
    let openid = wx.getStorageSync('openid')
    //  console.log({openid})
    let option = {
      value
    }
    if (openid) {
      // 检测敏感词
      wx.cloud.callFunction({
        name: 'msgsec',
        data: {
          content: JSON.stringify(option),
          openid
        },
        async success(res) {
          let {
            result: {
              errCode,
              errMsg
            }
          } = res;
          // console.log('检测结果:',res);//  errCode == 0 表示文本正常
          if (errCode == 0) {
            // 添加计划
            await todolist.where({
                task_id
              })
              .update({
                data: {
                  checked: false,
                  text: value
                }
              }).then(
                rows => {
                  // console.log(3.0, rows)
                  if (rows.errMsg == "collection.update:ok" || rows.errMsg == "document.update:ok") {
                    wx.showToast({
                      title: '修改计划成功。',
                      icon: 'none'
                    })
                    that.setData({
                      show3: false,
                      message: ''
                    })
                    that.taskList();
                  } else {
                    wx.showToast({
                      title: '修改计划失败。',
                      icon: 'none'
                    })
                  }
                },
                err => {
                  console.log(err)
                }
              )
          } else {
            if (errMsg != "openapi.security.msgSecCheck:ok") {
              wx.showToast({
                title: '您输入的内容包含敏感词哦。',
                icon: 'none'
              })
            } else {
              wx.showToast({
                title: `${errMsg},${errCode}`,
                icon: 'none'
              })
            }
          }
        }
      })
    } else {
      wx.showToast({
        title: '请先登录再写计划列表。',
        icon: 'none'
      })
    }
  },
  // 编辑（弹出层）
  editFn(e) {
    let task_id = e.currentTarget.dataset.id;
    let text = e.currentTarget.dataset.text;
    if (task_id) {
      this.setData({
        show3: true,
        message: text,
        task_id
      })
    }
  },
  // 删除
  removeFn(e) {
    let task_id = e.currentTarget.dataset.id;
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定删除该计划吗?',
      complete: (res) => {
        if (res.cancel) {

        }
        if (res.confirm) {
          todolist.where({
            task_id
          }).remove().then(
            content => {
              // console.log('111', content)
              let {
                errMsg
              } = content;
              if (errMsg == "collection.remove:ok") {
                let arr = that.data.arr;
                let newArr = arr.filter(item => {
                  if (item.task_id != task_id) {
                    return item
                  }
                })
                that.setData({
                  arr: newArr
                })
                that.initFn()
              } else {
                wx.showToast({
                  title: '删除计划失败。',
                  icon: 'none'
                })
              }
            }
          )
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.taskList();
    this.initFn();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})